package 练习07_多线程lock实现生产者消费者问题.练习03_多线程交互实现生产者消费者问题;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: MyStack
 * @Author: AllenSun
 * @Date: 2022/3/18 下午11:20
 */
public class MyStack<T> {
    LinkedList<T> values = new LinkedList<T>();

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void push(T t) {
        try {
            lock.lock();
            while (values.size() >= 200) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            condition.signalAll();
            values.addLast(t);
        } finally {
            lock.unlock();
        }

    }

    public T pull() {
        T t=null;
        try {
            lock.lock();
            while (values.isEmpty()) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            condition.signalAll();
            t= values.removeLast();
        } finally {
            lock.unlock();
        }
        return t;
    }

    public T peek() {
        return values.getLast();
    }
}
